<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>三级联动</title>
        <style>
            select {
                margin-right: 20px;
            }
        </style>
    </head>
    <body>
        <span>请选择省份</span>
        <select id="province">
            <option></option>
        </select>
        <span>请选择城市</span>
        <select id="city">
            <option></option>
        </select>
        <span>请选择县区</span>
        <select id="area">
            <option></option>
        </select>
    </body>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="./template-web.js"></script>
    <script type="text/html" id="plt-data">
        {{each data}}
        <option value="{{$value.code}}">{{$value.name}}</option>
        {{/each}}
    </script>
    <script>
        // 渲染的函数
        function renderData(obj, data) {
            let htmlStr = template('plt-data', { data: data })
            $(obj).html(htmlStr)
        }

        /*  
        ajax可以用来请求本地文件
        需要使用 live server 打开
    */
        $.ajax({
            url: './areatree-master/json/province.json',
            success(data) {
                // console.log('省份', data)
                renderData('#province', data)
            },
        })

        $.ajax({
            url: './areatree-master/json/city.json',
            success(data) {
                // console.log('市级', data)
                let code = $('#province').val()
                renderData('#city', data[code])
                $('#province').on('click', function () {
                    let provinceCode = $(this).val()
                    renderData('#city', data[provinceCode])
                })
            },
        })

        $.ajax({
            url: './areatree-master/json/area.json',
            success(data) {
                // console.log('区县', data)
                let code = $('#city').val()
                renderData('#area', data[code])
                $('#city').on('click', function () {
                    let cityCode = $(this).val()
                    renderData('#area', data[cityCode])
                })
            },
        })
    </script>
</html>
